# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------



# ----------------------------------------------------------------------------
# Use to receive IRF events
# from IR USB Receiver
# Receiving data / USB 
# Require pyUSB 1.0
# with Python 2.7.x and 3.x
# ----------------------------------------------------------------------------

import logging
logger = logging.getLogger()

try:
    from .devcomm.devusb import DEVusb
except ImportError as e:
    logger.debug("%s : %s", repr(e.__class__), str(e))
    from .devcomm.devusb0 import DEVusb


class IRECV(DEVusb):
    vendorId = 0x147a
    productId = 0xe03e
    read_endpoint = 0x82

    def __init__(self,port=None):
        DEVusb.__init__(self,port)
        self._id = '147a:e03e'
        self.idcontroller = 'IRECV'
        self.read_endpoint = 0x82
        self.RXcap = True
        self.TXcap = False
        self.setup = False

    def tsetup(self):
        self.open()
        try:
            logger.debug("Test reading %s....",self.idcontroller)
            data = self.read(100)
        except:
            self.opened = False
        if self.opened:
            logger.warning("%s Ready....",self.idcontroller)
            self.setup = True
            self.device = self.idcontroller + '-' + self.port
        return

    def request(self,rcmd):
        return None

    def plsend(self):
        return None

    def rfsend(self):
        return None

    def rxdata(self):
        """
        """
        data = self.read()
        if data:
             return " ".join(["0x%02x" % i for i in data[:10]])
        return None

    def rxevents(self,maxfrag=20,maxloop=100):
        """
        Read all data
        Cut down data / Count n fragment (max = 20)
        and eliminate same fragments
        maxloop = 100 (1s)
        """
        if maxfrag > 20: maxfrag = 20
        events = []
        n = 0
        while n < maxloop :
            data = self.rxdata()
            if data :
                if data not in events:
                    events.append(data)
            else:
                n += 1
            if len(events) > maxfrag:
                break
        if (n > maxloop) and len(events) == 0:
            events = None
        return events

    def rxevent(self,index=0,maxfrag=20,maxloop=100):
        """
        Read all data
        Cut down data / Count n fragment (max = 20)
        and eliminate same fragments
        maxloop = 100 (1s)
        return item at index
        """
        if maxfrag > 20: maxfrag = 20
        events = []
        n = 0
        while n < maxloop :
            data = self.rxdata()
            if data :
                if data not in events:
                    events.append(data)
            else:
                n += 1
            if len(events) == maxfrag:
                break
        if (n > maxloop) and len(events) == 0:
            events = None
        if events :
            return events[index]
        return None

